//
//  YGMapVC.m
//  map
//
//  Created by 黄德玉 on 2017/2/15.
//  Copyright © 2017年 黄德玉. All rights reserved.
//

#import "YGMapVC.h"
#import "MAMapKit.framework/Headers/MAMapKit.h"
#import "AMapSearchKit.framework/Headers/AMapSearchKit.h"
#import "YGMapView.h"
#define MAP_HEIGHT 250
@interface YGMapVC ()<UITableViewDelegate,UITableViewDataSource,UISearchBarDelegate,YGMapViewDelegate,AMapSearchDelegate>
@property(nonatomic,strong)UITableView * tableView;
@property(nonatomic,strong)UISearchBar * searchBar;
@property(nonatomic,strong) YGMapView * mapView;
@property(nonatomic,strong) AMapSearchAPI * mapSearch;
@property(nonatomic,copy) NSArray<AMapPOI *> * searchResult;  //兴趣点信息
@end

@implementation YGMapVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.title = @"收货地址";
    [self _addRightBtn];
    [self.view addSubview:self.tableView];
    
}
-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    //self.navigationController.hidesBarsWhenKeyboardAppears = NO;
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}
#pragma mark - tableView Delegate
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.searchResult.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
    }
    cell.textLabel.text = self.searchResult[indexPath.row].name;
    return cell;
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return self.mapView;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return MAP_HEIGHT;
}
#pragma mark - searchBar Delegate
- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar{
    [searchBar setShowsCancelButton:YES animated:YES];
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    return YES;
}
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar{
}
- (BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar{
    return YES;
}
- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar{
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    [searchBar setShowsCancelButton:NO animated:YES];
}
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
}
- (BOOL)searchBar:(UISearchBar *)searchBar shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    return YES;
}
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar{
    [self.view endEditing:YES];
}
-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    [self.view endEditing:YES];
}

#pragma mark - mapViewDelegate
-(void)centerChangedWithLocation:(CLLocationCoordinate2D)location{
    NSLog(@"中心点的坐标是%f,%f",location.latitude,location.longitude);
    [self.mapSearch cancelAllRequests]; //每次查询先取消所有进行中的查询.
//    AMapPOIAroundSearchRequest * request = [[AMapPOIAroundSearchRequest alloc] init];
//    request.location = [AMapGeoPoint locationWithLatitude:location.latitude longitude:location.longitude];
//    request.requireExtension = YES;
//    [self.mapSearch AMapPOIAroundSearch:request];
    
    AMapReGeocodeSearchRequest *regeo = [[AMapReGeocodeSearchRequest alloc] init];
    regeo.location = [AMapGeoPoint locationWithLatitude:location.latitude longitude:location.longitude];
    regeo.requireExtension = YES;
    [self.mapSearch AMapReGoecodeSearch:regeo];
}

#pragma mark - mapSearch Delegate
/**
 * @brief 当请求发生错误时，会调用代理的此方法.
 * @param request 发生错误的请求.
 * @param error   返回的错误.
 */
- (void)AMapSearchRequest:(id)request didFailWithError:(NSError *)error{
    NSLog(@"发生错误");
}

/**
 * @brief POI查询回调函数
 * @param request  发起的请求，具体字段参考 AMapPOISearchBaseRequest 及其子类。
 * @param response 响应结果，具体字段参考 AMapPOISearchResponse 。
 */
- (void)onPOISearchDone:(AMapPOISearchBaseRequest *)request response:(AMapPOISearchResponse *)response{
    NSLog(@"兴趣点查询回调");
    self.searchResult = [response.pois copy];
    for (AMapPOI * poi in response.pois) {
        NSLog(@"兴趣点的详细信息:%@,%@", poi.name,poi.address);
    }
    [self.tableView reloadData];
}

/**
 * @brief 沿途查询回调函数 (since v4.3.0)
 * @param request  发起的请求，具体字段参考 AMapRoutePOISearchRequest 及其子类。
 * @param response 响应结果，具体字段参考 AMapRoutePOISearchResponse 。
 */
- (void)onRoutePOISearchDone:(AMapRoutePOISearchRequest *)request response:(AMapRoutePOISearchResponse *)response{
    NSLog(@"沿途查询回调");
}

/**
 * @brief 地理编码查询回调函数
 * @param request  发起的请求，具体字段参考 AMapGeocodeSearchRequest 。
 * @param response 响应结果，具体字段参考 AMapGeocodeSearchResponse 。
 */
- (void)onGeocodeSearchDone:(AMapGeocodeSearchRequest *)request response:(AMapGeocodeSearchResponse *)response{
    NSLog(@"地理编码查询回调%@",response.geocodes);
}

/**
 * @brief 逆地理编码查询回调函数
 * @param request  发起的请求，具体字段参考 AMapReGeocodeSearchRequest 。
 * @param response 响应结果，具体字段参考 AMapReGeocodeSearchResponse 。
 */
- (void)onReGeocodeSearchDone:(AMapReGeocodeSearchRequest *)request response:(AMapReGeocodeSearchResponse *)response{
    NSLog(@"逆地理编码查询回调%@",response.regeocode.formattedAddress);
    self.searchResult = [response.regeocode.pois copy];
    [self.tableView reloadData];
}

/**
 * @brief 输入提示查询回调函数
 * @param request  发起的请求，具体字段参考 AMapInputTipsSearchRequest 。
 * @param response 响应结果，具体字段参考 AMapInputTipsSearchResponse 。
 */
- (void)onInputTipsSearchDone:(AMapInputTipsSearchRequest *)request response:(AMapInputTipsSearchResponse *)response{
    NSLog(@"输入提示查询回调");
}


#pragma mark - action
-(void)rightBtnClicked{
    NSLog(@"确定点击");
}

#pragma mark - private methods
-(void)_addRightBtn{
    UIBarButtonItem * barItem = [[UIBarButtonItem alloc] initWithTitle:@"确定" style:UIBarButtonItemStyleDone target:self action:@selector(rightBtnClicked)];
    self.navigationItem.rightBarButtonItem = barItem;
}
-(UIImage *)_imageWithColor:(UIColor *)color {
    CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, color.CGColor);
    CGContextFillRect(context, rect);
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}
#pragma mark - 初始化
-(UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:self.view.bounds];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.tableHeaderView = self.searchBar;
        _tableView.tableFooterView = [UIView new];
    }
    return _tableView;
}
-(YGMapView *)mapView{
    if (!_mapView) {
        _mapView = [[YGMapView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, MAP_HEIGHT)];
        _mapView.delegate = self;
    }
    return _mapView;
}
-(UISearchBar *)searchBar{
    if (!_searchBar) {
        _searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 50)];
        _searchBar.placeholder = @"搜索地点";
        _searchBar.delegate = self;
        _searchBar.backgroundImage = [self _imageWithColor:[UIColor whiteColor]];
        if (_searchBar.subviews.count > 0) {
            UIView * subView = _searchBar.subviews[0];
            [subView.subviews enumerateObjectsUsingBlock:^(__kindof UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                if ([obj isKindOfClass:NSClassFromString(@"UISearchBarTextField")]) {
                    NSLog(@"得到文本编辑框");
                    obj.layer.cornerRadius = 15.0;
                    obj.layer.masksToBounds  = YES;
                    obj.backgroundColor = [UIColor colorWithWhite:0.8 alpha:0.8];
                }
            }];
        }
    }
    return _searchBar;
}
-(AMapSearchAPI *)mapSearch{
    if (!_mapSearch) {
        _mapSearch = [[AMapSearchAPI alloc] init];
        _mapSearch.delegate = self;
        //[_mapSearch cancelAllRequests];
    }
    return _mapSearch;
}

@end
